﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Net.Http;
using System.Net.Http.Json;
using System.Threading.Tasks;
using Windows_AI_Assistant.Models;

namespace Windows_AI_Assistant.ViewModels.Pages
{
    public partial class EnrollViewModel : ObservableObject
    {
        private readonly HttpClient _httpClient = new();
        private readonly string _flaskUrl = "http://127.0.0.1:8080"; // Flask API 地址

        [ObservableProperty]
        private string? userName;

        [ObservableProperty]
        private string? setStatus;

        [ObservableProperty]
        private string? getStatus;

        [ObservableProperty]
        private string? identifiedUser;

        [ObservableProperty]
        private ObservableCollection<User> _users;

        [ObservableProperty]
        private int _currentPage;

        [ObservableProperty]
        private int _totalPages;

        private const int _perPage = 5;

        public EnrollViewModel()
        {
            // 初始化用户数据
            Users = new ObservableCollection<User>();
            CurrentPage = 1;
            FetchUsersAsync(CurrentPage);
        }

        [RelayCommand]
        public async Task EnrollAsync()
        {
            try
            {
                SetStatus = "Recording voice for enrollment...";
                string audioPath = await RecordAudioAsync("enroll_audio.wav");

                if (UserName != null)
                {
                    using var content = new MultipartFormDataContent
                    {
                        { new StringContent(UserName), "name" },
                        { new StreamContent(File.OpenRead(audioPath)), "audio", "enroll_audio.wav" }
                    };

                    var response = await _httpClient.PostAsync($"{_flaskUrl}/enroll", content);
                    response.EnsureSuccessStatusCode();

                    var result = await response.Content.ReadFromJsonAsync<EnrollResponse>();
                    if (result != null)
                    {
                        SetStatus = $"Enrollment complete. User ID: {result.Id}";
                        // 重新获取用户列表以包含新用户
                        FetchUsersAsync(CurrentPage);
                    }
                }
            }
            catch (System.Exception ex)
            {
                SetStatus = $"Enrollment failed: {ex.Message}";
            }
        }

        [RelayCommand]
        public async Task IdentifyAsync()
        {
            try
            {
                GetStatus = "Recording voice for identification...";
                string audioPath = await RecordAudioAsync("identify_audio.wav");

                using var content = new MultipartFormDataContent
                {
                    { new StreamContent(File.OpenRead(audioPath)), "audio", "identify_audio.wav" }
                };

                var response = await _httpClient.PostAsync($"{_flaskUrl}/identify", content);
                response.EnsureSuccessStatusCode();

                var result = await response.Content.ReadFromJsonAsync<IdentifyResponse>();
                if (result != null)
                {
                    IdentifiedUser = $"User: {result.Name} (ID: {result.Id})";
                    GetStatus = "Identification successful.";
                }
            }
            catch (System.Exception ex)
            {
                GetStatus = $"Identification failed: {ex.Message}";
            }
        }

        [RelayCommand]
        public async Task FetchUsersAsync(int page)
        {
            try
            {
                var response = await _httpClient.GetAsync($"{_flaskUrl}/get_users?page={page}");
                response.EnsureSuccessStatusCode();

                var result = await response.Content.ReadFromJsonAsync<UsersResponse>();
                if (result != null)
                {
                    Users.Clear();
                    foreach (var user in result.Users)
                    {
                        Users.Add(user);
                    }
                    CurrentPage = result.Page;
                    TotalPages = result.TotalPages;
                }
            }
            catch (System.Exception ex)
            {
                GetStatus = $"Failed to fetch users: {ex.Message}";
            }
        }

        [RelayCommand]
        public async Task DeleteUserAsync(string userId)
        {
            if (userId != null)
            {
                try
                {
                    Debug.WriteLine($"Deleting user with ID: {userId}");

                    var response = await _httpClient.DeleteAsync($"{_flaskUrl}/delete_user?user_id={userId}");
                    response.EnsureSuccessStatusCode();

                    var result = await response.Content.ReadFromJsonAsync<DeleteResponse>();
                    if (result != null)
                    {
                        GetStatus = result.Message;
                        Debug.WriteLine($"Delete response: {result.Message}");

                        // 删除成功后重新获取用户列表
                        FetchUsersAsync(CurrentPage);
                    }
                }
                catch (System.Exception ex)
                {
                    GetStatus = $"Failed to delete user: {ex.Message}";
                    Debug.WriteLine($"Exception: {ex.Message}");
                }
            }
            else
            {
                GetStatus = "No user selected for deletion.";
                Debug.WriteLine("No user selected for deletion.");
            }
        }

        private async Task<string> RecordAudioAsync(string filePath)
        {
            string tempFolderPath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Temp");
            filePath = System.IO.Path.Combine(tempFolderPath, filePath);
            // 使用 NAudio 录制音频
            using var waveIn = new NAudio.Wave.WaveInEvent();
            waveIn.WaveFormat = new NAudio.Wave.WaveFormat(16000, 1);
            var writer = new NAudio.Wave.WaveFileWriter(filePath, waveIn.WaveFormat);

            waveIn.DataAvailable += (s, e) => writer.Write(e.Buffer, 0, e.BytesRecorded);
            waveIn.StartRecording();

            await Task.Delay(5000); // 录音 5 秒
            waveIn.StopRecording();
            writer.Dispose();

            return filePath;
        }

        public event PropertyChangedEventHandler PropertyChanged;

        protected void OnPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

        [RelayCommand]
        public void Refresh()
        {
            FetchUsersAsync(CurrentPage);
        }
    }

    public class UsersResponse
    {
        public int Page { get; set; }
        public int TotalPages { get; set; }
        public List<User> Users { get; set; }
    }

    public class User
    {
        public string Id { get; set; }
        public string Name { get; set; }
    }

    public class EnrollResponse
    {
        public string Id { get; set; }
    }

    public class IdentifyResponse
    {
        public string Id { get; set; }
        public string Name { get; set; }
    }

    public class DeleteResponse
    {
        public string Message { get; set; }
    }
}
